package com.hkts.naturalgasauthentication.management.controller;


import com.hkts.management.common.utils.Result;
import com.hkts.management.common.utils.ResultUtil;
import com.hkts.naturalgasauthentication.management.entity.MapDepot;
import com.hkts.naturalgasauthentication.management.service.MapDepotService;
import com.hkts.naturalgasauthentication.utils.FtpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图库
 */
@Controller
@RequestMapping("/authentication/mapDepot")
public class MapDepotController {

    @Autowired
    private MapDepotService mapDepotService;

    @ResponseBody
    @RequestMapping("/getAll")
    public Result getAllPhoto(){
        List<MapDepot> all = mapDepotService.getAll();
        if (all == null || all.size() == 0){
            ResultUtil.error("暂无图片");
        }
        List<Map<String,String>> list = new ArrayList<>();
        for (int i = 0; i < all.size(); i++) {
            Map<String,String> id = new HashMap<>();
            String url = all.get(i).getUrl();
            id.put("id",all.get(i).getId());
            id.put("image",url);
            list.add(id);
        }
        return ResultUtil.data(list);
    }
    @ResponseBody
    @RequestMapping(value = "/showImage")
    public void update(@RequestParam("id") String id, HttpServletRequest request, HttpServletResponse response) {
        MapDepot mapDepot = mapDepotService.get(id);
        if(mapDepot!=null){
            String url = mapDepot.getUrl();
            byte[] bytes = FtpUtil.putImages(url);
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/png");
            OutputStream outputStream = null;
            try {
                outputStream = response.getOutputStream();
                outputStream.write(bytes);
                outputStream.flush();//排出流中所有数据
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    outputStream.close();//关闭流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
